<template>
  <div class="p-2">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>
    <el-drawer class="hm-drawer" v-model="dialog.visible" size="40%" direction="rtl">
      <template #header>
        <div class="hm-box-title">{{ dialog.title }}</div>
      </template>
      <el-form ref="addressInfoFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="退货地址类型" prop="addressType">
          <el-select v-model="form.addressType" placeholder="请选择合作方式" clearable>
            <el-option v-for="dict in hm_addr_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="邮寄地址" prop="mailingAddress">
          <el-input v-model="form.mailingAddress" placeholder="请输入邮寄地址" clearable />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" clearable />
        </el-form-item>
        <el-form-item label="接收人" prop="recipient">
          <el-input v-model="form.recipient" placeholder="请输入接收人" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" clearable />
        </el-form-item>
        <el-form-item label="邮编" prop="postalCode">
          <el-input v-model="form.postalCode" placeholder="请输入邮编" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <el-row :gutter="20">
      <el-col :span="6" :xs="24" v-if="false">
        <el-card class="box-card" v-show="!dialog.visible">
          <div>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </div>
          <div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                退货地址类型
                <div class="pull-right">{{ filterAddrType(infoData.addressType) }}</div>
              </li>
              <li class="list-group-item">
                邮寄地址(xx省xx市xx区县)
                <div class="pull-right">{{ infoData.mailingAddress }}</div>
              </li>
              <li class="list-group-item">
                详细地址
                <div class="pull-right">{{ infoData.detailedAddress }}</div>
              </li>
              <li class="list-group-item">
                接收人
                <div class="pull-right">{{ infoData.recipient }}</div>
              </li>
              <li class="list-group-item">
                手机号
                <div class="pull-right">{{ infoData.phone }}</div>
              </li>
              <li class="list-group-item">
                手机邮编号
                <div class="pull-right">{{ infoData.postalCode }}</div>
              </li>
            </ul>
          </div>
        </el-card>
        <el-card v-show="dialog.visible">
          <el-form ref="addressInfoFormRef" :model="form" :rules="rules" label-width="200px">
            <el-form-item label="退货地址类型" prop="addressType">
              <el-select v-model="form.addressType" placeholder="请选择合作方式">
                <el-option v-for="dict in hm_addr_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="邮寄地址(xx省xx市xx区县)" prop="mailingAddress">
              <el-input v-model="form.mailingAddress" placeholder="请输入邮寄地址(xx省xx市xx区县)" />
            </el-form-item>
            <el-form-item label="详细地址" prop="detailedAddress">
              <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" />
            </el-form-item>
            <el-form-item label="接收人" prop="recipient">
              <el-input v-model="form.recipient" placeholder="请输入接收人" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入电话" />
            </el-form-item>
            <el-form-item label="邮编" prop="postalCode">
              <el-input v-model="form.postalCode" placeholder="请输入邮编" />
            </el-form-item>
          </el-form>
          <div class="dialog-footer">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" :xs="24">
        <el-card shadow="never">
          <el-table v-loading="loading" :data="addressInfoList" @selection-change="handleSelectionChange">
            <el-table-column label="退货类型" align="center" prop="addressType">
              <template #default="scope">
                {{ filterAddrType(scope.row.addressType) }}
              </template>
            </el-table-column>
            <el-table-column label="邮寄地址(xx省xx市xx区县)" align="center" prop="mailingAddress" />
            <el-table-column label="详细地址" show-overflow-tooltip align="center" prop="detailedAddress" />
            <el-table-column label="接收人" align="center" prop="recipient" />
            <el-table-column label="手机号" align="center" prop="phone" />
            <el-table-column label="邮编" align="center" prop="postalCode" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="AddressInfo" lang="ts">
import { listAddressInfo, getAddressInfo, delAddressInfo, addAddressInfo, updateAddressInfo } from '@/api/system/addressInfo';
import { AddressInfoVO, AddressInfoQuery, AddressInfoForm } from '@/api/system/addressInfo/types';
import { validateSpaceAndEmoji } from '@/utils/validate'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { hm_addr_type } = toRefs<any>(proxy?.useDict('hm_addr_type'));

const addressInfoList = ref<AddressInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const addressInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const infoData: AddressInfoForm = reactive({});

const initFormData: AddressInfoForm = {
  id: undefined,
  userId: undefined,
  addressType: undefined,
  mailingAddress: undefined,
  detailedAddress: undefined,
  recipient: undefined,
  phone: undefined,
  postalCode: undefined,
  delFlag: undefined,
  remark: undefined,
  createDept: undefined,
  createBy: undefined,
  createTime: undefined,
  updateBy: undefined,
  updateTime: undefined
};
const data = reactive<PageData<AddressInfoForm, AddressInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    addressType: undefined,
    mailingAddress: undefined,
    detailedAddress: undefined,
    recipient: undefined,
    phone: undefined,
    postalCode: undefined,
    delFlag: undefined,
    remark: undefined,
    createDept: undefined,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined,
  },
  rules: {
    addressType: [{ required: true, message: '退货类型不能为空', trigger: 'blur' }],
    mailingAddress: [{ required: true, message: '邮寄地址(xx省xx市xx区县)不能为空', trigger: 'blur' }, { validator: validateSpaceAndEmoji, }],
    detailedAddress: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }, { validator: validateSpaceAndEmoji, }],
    recipient: [{ required: true, message: '接收人不能为空', trigger: 'blur' }, { validator: validateSpaceAndEmoji, }],
    phone: [{ required: true, message: '电话不能为空', trigger: 'blur' }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
    postalCode: [{ required: true, message: '邮编不能为空', trigger: 'blur' }, { validator: validateSpaceAndEmoji, }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询地址管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAddressInfo(queryParams.value);
  addressInfoList.value = res.rows;
  Object.assign(infoData, res.rows[0]);
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  addressInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AddressInfoVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  dialog.visible = true;
  dialog.title = '添加地址管理';
  nextTick(() => {
    reset();
  });
};

/** 修改按钮操作 */
const handleUpdate = (row?: AddressInfoVO) => {
  loading.value = true;
  dialog.visible = true;
  dialog.title = '修改地址管理';
  nextTick(async () => {
    reset();
    const _id = row?.id || ids.value[0];
    const res = await getAddressInfo(_id);
    loading.value = false;
    Object.assign(form.value, res.data);
  });
};

/** 提交按钮 */
const submitForm = () => {
  addressInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAddressInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAddressInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AddressInfoVO) => {
  const _ids = row?.id || ids.value;
  let info = row?.detailedAddress;
  await proxy?.$modal.confirm('是否确认删除地址为" ' + info + ' "的数据项？').finally(() => (loading.value = false));
  await delAddressInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/addressInfo/export',
    {
      ...queryParams.value
    },
    `addressInfo_${new Date().getTime()}.xlsx`
  );
};

const filterAddrType = (para: any) => {
  let _label = '';
  hm_addr_type.value.forEach((item: any) => {
    if (item.value == String(para)) {
      _label = item.label;
    }
  });
  return _label;
};

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
:deep(.el-select) {
  width: 100%;
}
</style>
